package fastClient;

import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import encodeDecode.IOMessageDecoder;
import encodeDecode.IOMessageEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;

public class NettyClient implements Runnable{

	private ScheduledExecutorService executor = 
			Executors.newScheduledThreadPool(1);
	
	private String username;
	private String password;
	
	public NettyClient(String username, String password) {
		// TODO Auto-generated constructor stub
		this.username = username;
		this.password = password;
	}
	
	public void run() {
		
		try{
			connect();
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	public void connect()throws Exception{
		
		EventLoopGroup group = new NioEventLoopGroup();
		   try{
			   
			LoginAuthReqHandler.username = username;
			LoginAuthReqHandler.password = password;
			   
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
			 .option(ChannelOption.TCP_NODELAY, true)
			 .option(ChannelOption.SO_KEEPALIVE, true)
			 .option(ChannelOption.SO_REUSEADDR, true)
			 .handler(new ChannelInitializer<SocketChannel>() {
				 
				protected void initChannel(SocketChannel ch) throws Exception {
					
					ch.pipeline().addLast(new IOMessageDecoder(1024*1024, 0, 4));
					ch.pipeline().addLast(new IOMessageEncoder());
					ch.pipeline().addLast(new IdleStateHandler(0, 0, 40));
					ch.pipeline().addLast(new LoginAuthReqHandler());
					ch.pipeline().addLast(new HeartBeatReqHandler());
					ch.pipeline().addLast(new MesSyncClientHandler());
				}; 
			});
			
			ChannelFuture future = b.connect(
					new InetSocketAddress(NettyConstant.REMOTE_IP, NettyConstant.REMOTE_PORT)).sync();
			
			if(future.isSuccess())System.out.println("client success connect server !!");
			future.channel().closeFuture().sync();
			group.shutdownGracefully();

		}finally{
			
			executor.execute(new Runnable() {
				
				public void run() {
					// TODO Auto-generated method stub
					try{
						TimeUnit.SECONDS.sleep(10);
						try{
							System.out.println("Connect again-->");
							connect();
							
						}catch(Exception e){
							e.printStackTrace();
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			});
		}
	}
}
